package it.java.giw.dataextraction.aleph.wrapper.cinemadelsilenzio;

import it.java.giw.dataextraction.aleph.helper.CSVHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class CinemaSilenzioWrapperWorker implements Runnable {

	private LinkedBlockingQueue<String> datasetFiles;
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;
	private HashMap<String, String> attr2xpath;

	private List<String[]> results;
	private CSVHelper helper;

	/*EXAMPLES
    System.out.println(page.getTitleText());
    System.out.println(page.getHtmlElementById("footer"));
    //System.out.println(page.getAnchorByName("anchor_name"));

    //get list of all divs
    System.out.println(page.getByXPath("//div"));
    final String pageAsXml = page.asXml();
    System.out.println(pageAsXml.contains("<body class=\"composite\">"));
    final String pageAsText = page.asText();
    System.out.println(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
	 */

	public CinemaSilenzioWrapperWorker(LinkedBlockingQueue<String> datasetFiles, CountDownLatch startSignal, CountDownLatch doneSignal, CSVHelper helper) {
		this.datasetFiles = datasetFiles;
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.results = new ArrayList<String[]>();
		this.attr2xpath = new HashMap<String,String>();
		this.helper = helper;
		initMap();
	}

	private void initMap() {
		/* xpaths di cinemadelsilenzio */
		attr2xpath = new HashMap<String, String>();
		attr2xpath.put("title", "//h1[contains(@class,'body_title')]/a/text()");
		attr2xpath.put("directors", "//*[@id='dastampare']//table//td[1][b='regia']/../td[2]/a[contains(@href,'index.php?mod=star')]/text()");
		attr2xpath.put("genre", "//*[@id='dastampare']//table//td[1][b='genere']/../td[2]/a/text()");
		attr2xpath.put("year", "//*[@id='dastampare']//table//td[1][b='anno']/../td[2]/a/text()");
		attr2xpath.put("rating", "//*[@id='dastampare']//table//td[1][b='media voti redazione']/../td[2]//img/@src");
		attr2xpath.put("actors", "//*[@id='dastampare']//table//td[1][b='cast']/../td[2]/a/text()");
		attr2xpath.put("poster", "//td/a[contains(@href, 'index.php?mod=poster')]/img[@alt]/@src");
		attr2xpath.put("trailer", "//tr/td/a[contains(@href, 'index.php?mod=trailer&id')]/@href");
		/* fine xpaths cinemadelsilenzio */
	}

	public void run() {
		try {
			startSignal.await();
			while(!datasetFiles.isEmpty()){
				/* create webClient and set options to get only HTML */
				final WebClient webClient = new WebClient();
				//		webClient.getOptions().setThrowExceptionOnScriptError(false);
				webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
				webClient.getOptions().setCssEnabled(false);
				webClient.getOptions().setJavaScriptEnabled(false);
				webClient.getOptions().setAppletEnabled(false);

				HtmlPage page;
				try {
					String[] info = new String[9];
					for (int i = 0; i<info.length; i++)
						info[i] = "";
					String filename = datasetFiles.poll();
					System.out.println(filename);
					page = webClient.getPage("file:///C:/Users/Roberto/giw2/AlephDataExtractor/download/"+filename);
					//				    System.out.println(page.getByXPath("//h1[1]/text()"));
					info[0] = filename;
					//title
					info[1] = page.getByXPath(attr2xpath.get("title")).get(0).toString().replaceAll("Recensione: ", "");
					//director(s)
					info[2] = "";
					for (Object director : page.getByXPath(attr2xpath.get("directors")))
						info[2] += director.toString()+";";

					//genre
					info[3] = "";
					for (Object director : page.getByXPath(attr2xpath.get("genre")))
						info[3] += director.toString()+";";
					//year
					List<?> l = page.getByXPath(attr2xpath.get("year"));
					if (!l.isEmpty())
						info[4] = l.get(0).toString();
					//rating
					l = page.getByXPath(attr2xpath.get("rating"));
					if (!l.isEmpty()){
						String x = ((DomAttr)l.get(0)).getValue();
						info[5] = String.valueOf(Double.parseDouble(x.replaceAll("images/common/vote_","").replaceAll("\\.gif", ""))/10);
					}
						
//					DomAttr src = (DomAttr) page.getByXPath(attr2xpath.get("rating")).get(0);
//					info[5] = String.valueOf(Double.parseDouble(src.getValue().replaceAll("images/common/vote_","").replaceAll("\\.gif", ""))/10);
					//actors
					info[6] = "";
					for (Object actor : page.getByXPath(attr2xpath.get("actors")))
						info[6] += actor.toString()+";";
					//poster
					l = page.getByXPath(attr2xpath.get("poster"));
					if (!l.isEmpty())
						info[7] = ((DomAttr)l.get(0)).getValue();;
					
					//trailer (link)
					l = page.getByXPath(attr2xpath.get("trailer"));
					if (!l.isEmpty())
						info[8] = ((DomAttr)l.get(0)).getValue();
					
					results.add(info);

				} catch (FailingHttpStatusCodeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IndexOutOfBoundsException e){
					System.out.println("*** *** ***Errore nel parsing");
				}
			}
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			doneSignal.countDown();
		}finally{
			try {
				for(String[] row : results)
					helper.writeCSV(row,"Collection CinemaDelSilenzio.csv");
			} catch (Exception e) {
				e.printStackTrace();
			}
			doneSignal.countDown();
		}
	}
}
